package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.cart.entity.CartInfo;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.cart.CartFeignClient;
import com.atguigu.gmall.product.entity.SkuInfo;
import feign.Request;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Api(tags = "远程调用-购物车")// weball => cartFeign => service-cart
@Controller
public class CartController {

    @Autowired
    CartFeignClient cartFeignClient;
    //public static Map<Thread,HttpServletRequest> map = new ConcurrentHashMap<>();
    //public static ThreadLocal<HttpServletRequest> threadLocal = new ThreadLocal<>();
    //  http://cart.gmall.com/addCart.html?skuId=49&skuNum=1&sourceType=query
    @GetMapping("/addCart.html")
    public String addToCart (@RequestParam("skuId") Long skuId,
                             @RequestParam("skuNum") Integer skuNum,
                             //HttpServletRequest request,
                             Model model){

        //远程调用
        //map.put(Thread.currentThread(),request);
        //threadLocal.set(request);
        //通过传参的方式精确调整每个请求的超时时间
        Request.Options options = new Request.Options(1000,3000);
        Result<SkuInfo> result = cartFeignClient.addToCart(skuId, skuNum,options);
        //map.remove(Thread.currentThread()); //防止OOM
        //threadLocal.remove(request);
        //给前端返回的数据和页面
        model.addAttribute("skuInfo",result.getData());
        model.addAttribute("skuNum",skuNum);
        return "cart/addCart";
    }

    //页面跳转 交给 web-all
    //  http://cart.gmall.com/cart.html
    @GetMapping("/cart.html")
    public String cartListPage (){
        return "cart/index";
    }
    //删除选中的商品 发生页面跳转 ==> 重定向到原来的购物车页面
    // http://cart.gmall.com/cart/deleteChecked
    @GetMapping("//cart/deleteChecked")
    public String Page(){
        //远程调用
        cartFeignClient.deleteChecked();
        return "redirect:http://cart.gmall.com/cart.html";
    }
}
